package com.pignest.hotel.ajax;

import java.util.Date;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.directwebremoting.annotations.RemoteMethod;
import org.directwebremoting.annotations.RemoteProxy;

import com.pignest.framework.ajax.AjaxResult;
import com.pignest.hotel.beans.Card;
import com.pignest.hotel.beans.Living;
import com.pignest.hotel.beans.Member;
import com.pignest.hotel.beans.Room;
import com.pignest.hotel.beans.User;
import com.pignest.hotel.service.CardService;
import com.pignest.hotel.spring.Services;
import com.pignest.hotel.system.L;
import com.pignest.hotel.system.Permission;
import com.pignest.hotel.util.DateUtil;

@RemoteProxy
public class CardAjax extends HotelAjax {
	
	@RemoteMethod
	public String getRoomCardStatus(String roomName) {
		if (StringUtils.isEmpty(roomName))
			return "请输入房间号";
		Room room = Services.getRoomService().getRoomByName(roomName);
		if (room == null)
			return "无交房间号:" + roomName;
		if (StringUtils.isEmpty(room.getLockNumber()))
			return "该房间未设置锁号, 无法使用";
		Living living = Services.getReceptionService().getLiving(room);
		String r = "";
		if (living != null) {
			r = "顾客 " + living.getCustormName() + " 更好的住在房间" + roomName;
		} else {
			r = "房间" + roomName + "当前无人入住";
		}
		List<Card> cards = Services.getCardService().listCardsByLockNumber(room.getLockNumber());
		if (cards != null && !cards.isEmpty()) {
			int n = 0;
			long now = System.currentTimeMillis();
			for (Card card : cards) {
				if (card.getExpireTime() != null && card.getExpireTime().getTime() > now)
					n++;
			}
			r += ", 该房间已经配了" + cards.size() + "张卡";
			if (cards.size() == 1)
				r += "(卡号 " + cards.get(0).getCardNumber() + ")";
			if (cards.size() != n)
				r += ", 其中仅" + n + "张卡有效";
		} else {
			r += ", 未配卡";
		}
		return r;
	}
	
	/** 正常格式时间转为卡上的时间格式 */
	@RemoteMethod
	public String getCardFormatTime(String time) {
		Date t = DateUtil.toDate(time, "yyyy-MM-dd HH:mm");
		if (t == null)
			return null;
		return DateUtil.toString(t, Card.DATE_FORMAT);
	}
	
	@RemoteMethod
	public String[] makeCard(String serial, String roomName, String time) {
		Card card = Services.getCardService().getCardBySerialNumber(serial);
		if (card == null || !card.isEnable())
			error("无效卡");
		Room room = Services.getRoomService().getRoomByName(roomName);
		if (room == null)
			error("房间号不存在");
		Date t = DateUtil.toDate(time, "yyyy-MM-dd HH:mm");
		if (t == null)
			error("授权时间输入不合法");
		if (t.getTime() < System.currentTimeMillis())
			error("授权时间必须是在将来时");
		Services.getCardService().grantCard(card, room, t);
		L.update(card, "卡授权");
		return new String[] {card.getLockNumber(), DateUtil.toString(t, Card.DATE_FORMAT)};
	}
	
	@RemoteMethod
	public Card getCard(String cardId) {
		checkPermission(Permission.LOGIN);
		return Services.getCardService().getCard(cardId);
	}
	
	@RemoteMethod
	public String addCard(String serialNumber) {
		checkPermission(Permission.ADMINISTER);
		Card card = getCardBySerialNumber(serialNumber);
		if (card != null)
			return "卡片已经收录在系统中";
		card = new Card(serialNumber);
		Services.getCardService().insert(card);
		L.insert(card);
		return null;
	}
	
	@RemoteMethod
	public String enableCards(final boolean enable, String[] cardIds) {
		checkPermission(Permission.ADMINISTER);
		final Card[] cards = new Card[cardIds.length];
		final CardService service = Services.getCardService();
		for (int i = 0; i < cards.length; i++) {
			cards[i] = service.getCard(cardIds[i]);
			if (cards[i] == null) {
				return "没找到卡片: " + cardIds[i];
			}
		}
		service.executeInTransaction(new Runnable() {
			@Override
			public void run() {
				Date d = new Date();
				for (int i = 0; i < cards.length; i++) {
					cards[i].setEnable(enable);
					cards[i].setLastUpdateTime(d);
					service.update(cards[i]);
					L.enable(enable, cards[i]);
				}
			}
		});
		return null;
	}
	
	@RemoteMethod
	public String saveCardNumber(String serialNumber, String cardNumber) {
		checkPermission(Permission.ADMINISTER);
		if (StringUtils.isEmpty(cardNumber))
			return "请输入卡号";
		//XXX 卡号规则
//		int c = Utils.getInteger(cardNumber, -1);
//		if (c < 0 || c > 65535) {
//			return "卡号值为 0-65535 之间的数值";
//		}
		CardService service = Services.getCardService();
		Card card = service.getCardByCardNumber(cardNumber);
		if (card != null) {
			if (card.getSerialNumber().equals(serialNumber))
				return null;
			return "该卡号(" + cardNumber + ")已经存在";
		}
		card = getCardBySerialNumber(serialNumber);
		if (card == null)
			return "该卡片未在系统中录入:" + serialNumber;
		card.setCardNumber(cardNumber);
		card.setLastUpdateTime(new Date());
		Services.getCardService().update(card);
		L.update(card, "修改卡号");
		return null;
	}
	
	/**
	 * 销卡, 清除房间锁号和有效期, 
	 * */
	@RemoteMethod
	public boolean cancelCard(String serialNumber) {
		checkPermissionOr(Permission.ADMINISTER, Permission.RECEPTION);
		final Card card = getCardBySerialNumber(serialNumber);
		if (card == null)
			return false;
		Services.getCardService().cancelCard(card);
		return true;
	}
	
	/**
	 * 回收卡, 取消会员卡/员工卡/房卡
	 * */
	@RemoteMethod
	public boolean recycleCard(final String serialNumber) {
		checkPermissionOr(Permission.ADMINISTER, Permission.RECEPTION);
		final Card card = getCardBySerialNumber(serialNumber);
		if (card == null)
			return false;
		final CardService service = Services.getCardService();
		service.executeInTransaction(new Runnable() {
			@Override
			public void run() {
				card.setType(Card.TYPE_NORMAL);
				card.setHolderName(null);
				card.setLockNumber(null);
				card.setExpireTime(null);
				Services.getCardService().update(card);
				L.update(card, "回收卡");
				
				if (card.getType() == Card.TYPE_MEMBER) {
					Member m = service.getMemberByCard(serialNumber);
					if (m != null) {
						m.setCardNo(null);
						service.update(m);
						L.update(m, "回收卡");
					}
				} else if (card.getType() == Card.TYPE_USER) {
					User user = service.getUserByCard(serialNumber);
					if (user != null) {
						user.setCardNumber(null);
						service.update(user);
						L.update(user, "回收卡");
					}
				}
			}
		});
		return true;
	}
	
	public String getRoomNameByLockNumber(String lockNumber) {
		Room room = Services.getRoomService().getRoomByLock(lockNumber);
		if (room == null)
			return null;
		return room.getName();
	}
	
	@RemoteMethod
	public String getCardDetail(String cardId) {
		checkPermission(Permission.LOGIN);
		Card card = getCard(cardId);
		if (card == null)
			return "没找到卡片: " + cardId;
		return getCardDetail(card);
	}
	
	@RemoteMethod
	public String getCardDetailBySerialNumber(String serialNumber) {
		checkPermission(Permission.LOGIN);
		Card card = getCardBySerialNumber(serialNumber);
		if (card == null)
			return "没找到卡片 : " + serialNumber;
		return getCardDetail(card);
	}
	
	private String getCardDetail(Card card) {
		StringBuilder sb = new StringBuilder();
		sb.append("<li><label>序列号</label>&nbsp;").append(card.getSerialNumber()).append("</li>");
		sb.append("<li><label>卡号</label>&nbsp;").append(v(card.getCardNumber())).append("</li>");
		sb.append("<li><label>类型</label>&nbsp;").append(card.getType2()).append("</li>");
		sb.append("<li><label>持有者</label>&nbsp;").append(v(card.getHolderName())).append("</li>");
		sb.append("<li><label>状态</label>&nbsp;").append(card.getEnable2()).append("</li>");
		sb.append("<li><label>锁号</label>&nbsp;").append(v(card.getLockNumber())).append("</li>");
		if (StringUtils.isNotEmpty(card.getLockNumber())) {
			Room room = Services.getRoomService().getRoomByLock(card.getCardNumber());
			if (room != null) {
				sb.append("<li><label>关联房间</label>&nbsp;").append(v(room.getName())).append("</li>");
			}
		}
		sb.append("<li><label>有效期</label>&nbsp;").append(card.getExpireTime3()).append("</li>");
		return sb.toString();
	}

	@RemoteMethod
	public Card getCardBySerialNumber(String serialNumber) {
		checkPermission(Permission.LOGIN);
		return Services.getCardService().getCardBySerialNumber(serialNumber);
	}
	
	@RemoteMethod
	public AjaxResult selfServiceLiving(String serialNumber) {
		checkPermission(Permission.SELF_SERVICE);
		CardService service = Services.getCardService();
		Card card = service.getUsableMemberCard(serialNumber);
		if (card == null)
			return AjaxResult.fail("该卡未被授权, 或者已经被禁用");
		Member member = service.getMemberByCard(serialNumber);
		if (member == null || member.getMemberLevel() == null)
			return AjaxResult.fail("数据错误");
		if (!"是".equals(member.getMemberLevel().getSelfhelplive()))
			return AjaxResult.fail("当前会员等级为: " + member.getMemberLevel().getMemberlevel() + ", 无法进行自助入住, 请到前台办理");
		return AjaxResult.success();
	}
	
	@RemoteMethod
	public AjaxResult selfServiceCheckOut(String serialNumber) {
		checkPermission(Permission.SELF_SERVICE);
		CardService service = Services.getCardService();
		Card card = service.getUsableMemberCard(serialNumber);
		if (card == null)
			return AjaxResult.fail("该卡未被授权, 或者已经被禁用");
		Member member = service.getMemberByCard(serialNumber);
		if (member == null || member.getMemberLevel() == null)
			return AjaxResult.fail("数据错误");
		if (!"是".equals(member.getMemberLevel().getSelfhelpout()))
			return AjaxResult.fail("当前会员等级为: " + member.getMemberLevel().getMemberlevel() + ", 无法进行自助入住, 请到前台办理");
		return AjaxResult.success();
	}
	
	@RemoteMethod
	public void noop() {
	}
	
//	@RemoteMethod
//	public String addCard(String serialNumber, String cardNumber) {
//		Card card = getCardBySerialNumber(serialNumber);
//		if (card != null) {
//			return "卡已经存在";
//		}
//		card = new Card(serialNumber);
//		Services.getCardService().insert(card);
//		return null;
//	}
	
//	@RemoteMethod
//	public String enableCards(boolean enable, String[] cardIds) {
//		if (cardIds == null || cardIds.length == 0)
//			return null;
//		List<Card> cards = new ArrayList<Card>();
//		CardService service = Services.getCardService();
//		for (int i = 0; i < cardIds.length; i++) {
//			Card card = service.getCard(cardIds[i]);
//			if (card != null) {
//				card.setEnable(enable);
//				cards.add(card);
//			}
//		}
//		if (cards.size() > 0) {
//			service.saveAll(cards);
//		}
//		return null;
//	}
	
//	@RemoteMethod
//	public String setCardNumber(String cardId, String cardNumber) {
//		Card card = getCard(cardId);
//		if (card == null) {
//			return "卡不存在";
//		}
//		card.setCardNumber(cardNumber);
//		Services.getCardService().update(card);
//		return null;
//	}
	
	private String v(String str) {
		if (StringUtils.isBlank(str))
			return "";
		return str;
	}
}
